/*
 * Created: 2022-09-18 13:10:04
 * Author : 涛涛涛
 */

import { useMyReducer } from '@/utils';
import { Product_Web } from '@/pages/_server/_class/Product/Product';
import { apiGetIntactProductList } from '@/pages/_server/_api/ApiProduct/apiGetIntactProductList';
import { useEffect, useMemo, useRef } from 'react';
import _ from 'lodash';
import Taro from '@tarojs/taro';
type SearchStatus = 'loading' | 'list' | 'nothing' | 'history';
export class SearchClass {
    /** 列表显示状态 */
    status: SearchStatus = 'history';
    /** 搜索关键字 */
    keywords: string = '';
    /** 商品列表数据 */
    productList: Product_Web[] = [];
    /** 历史记录列表 */
    historyRecordList: string[] = [];
}
/** 设置Reducer */
export const useSearchReducer = () => {
    const [searchReducer, searchDispatch] = useMyReducer({
        initializer: new SearchClass(),
        handleMapper: {
            /** 搜索关键字 */
            setKeywords(state, payload: string) {
                const newState = { ...state };
                newState.keywords = payload;
                if (!newState.keywords) newState.status = 'history';
                return newState;
            },
            /** 设置列表状态 */
            setStatus(state, payload: SearchStatus) {
                const newState = { ...state };
                newState.status = payload;
                return newState;
            },
            /** 设置商品列表 */
            setProductList(state, payload: Product_Web[]) {
                const newState = { ...state };
                if (payload && payload.length > 0) {
                    newState.status = 'list';
                    newState.productList = payload;
                } else {
                    newState.status = 'nothing';
                    newState.productList = [];
                }
                return newState;
            },
            /** 设置历史记录 */
            saveHistoryRecord(state, payload: string) {
                if (!payload) return state;
                const newState = { ...state };
                let list = [...newState.historyRecordList];
                const index = list.indexOf(payload);
                if (index !== -1) {
                    const temp = list.splice(index, 1);
                    list = [...list, temp[0]];
                } else {
                    list.push(payload);
                }
                newState.historyRecordList = list;
                Taro.setStorageSync('history-record', JSON.stringify(list));
                return newState;
            },
            /** 初始化历史记录 */
            initHistoryRecordList(state, payload?: undefined) {
                const newState = { ...state };
                const records: string[] = JSON.parse(Taro.getStorageSync('history-record') || '[]');
                if (records.length === 0) newState.status = 'nothing';
                newState.historyRecordList = records;
                return newState;
            },
        },
    });
    setTimeout(() => {
        console.log(searchReducer);
    }, 1000);
    useEffect(() => {
        searchDispatch({
            type: 'initHistoryRecordList',
        });
    }, [searchDispatch]);
    /** 获得列表数据的节流函数 */
    const fetchProductList = useMemo(() => {
        return _.throttle((keywords: string) => {
            if (!keywords) {
                if (searchReducer.historyRecordList.length > 0) {
                    searchDispatch({ type: 'setStatus', payload: 'history' });
                } else {
                    searchDispatch({ type: 'setStatus', payload: 'nothing' });
                }
                return;
            }
            searchDispatch({ type: 'setStatus', payload: 'loading' });
            apiGetIntactProductList().then((response) => {
                if (!response) {
                    searchDispatch({ type: 'setProductList', payload: [] });
                    return;
                }
                searchDispatch({ type: 'setProductList', payload: response.data });
                // searchDispatch({ type: 'setProductList', payload: [] });
            });
        }, 1000);
    }, [searchDispatch, searchReducer.historyRecordList]);

    /** 每当关键字变化,都要发送一次请求 */
    useEffect(() => {
        fetchProductList(searchReducer.keywords);
    }, [fetchProductList, searchReducer.keywords]);

    return {
        searchReducer,
        searchDispatch,
        fetchProductList,
    };
};
